package com.sensetime.jv.config;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sensetime.jv.entity.ReturnWrapper;
import feign.Response;
import feign.codec.Decoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.lang.reflect.Type;

public class ReturnWrapperDecoder implements Decoder {

    private static final Logger log = LoggerFactory.getLogger(ReturnWrapperDecoder.class);
    private final Decoder delegate;
    private final ObjectMapper objectMapper;

    public ReturnWrapperDecoder(Decoder delegate, ObjectMapper objectMapper) {
        this.delegate = delegate;
        this.objectMapper = objectMapper;
    }

    @Override
    public Object decode(Response response, Type type) throws IOException {
//        log.info("Decoding response for type: {}", type.getTypeName());

        // 读取响应体
        String responseBody = new String(response.body().asInputStream().readAllBytes());
//        log.info("Response body: {}", responseBody);

        try {
            // 无论原始类型如何，都尝试将其包装为 ReturnWrapper<T>
            JavaType actualType = objectMapper.constructType(type);
            JavaType wrapperType = objectMapper.getTypeFactory()
                    .constructParametricType(ReturnWrapper.class, actualType);

            // 解析为 ReturnWrapper
            ReturnWrapper<?> returnWrapper = objectMapper.readValue(responseBody, wrapperType);

            if (returnWrapper != null) {
//                log.info("Successfully decoded ReturnWrapper with data: {}", returnWrapper.getData());
                return returnWrapper.getData();
            }

            // 解码失败，使用默认解码器
            return delegate.decode(response, type);

        } catch (Exception e) {
            log.error("Failed to decode response as ReturnWrapper", e);
            // 解码失败时，尝试使用默认解码器
            return delegate.decode(response, type);
        }
    }
}